const shop = require('../../providers/dataAccess').shop;
const cartService = require('../cartService/cartService');
const skuService = require('../productService/skuService');

const OrderService = function () {
  /*订单列表*/
  const _orderlist = async (appId,userId,offset,limit,type) => {
    let where = "";
    if(type >= 0 && parseInt(type) > -1){
      where = ' AND orders.orderStatus = ' + parseInt(type);
	  }
    let szQuery = "SELECT orders.id,payAmount,orderStatus,orderAmount,productAmount,orderNo,addTime,shippingTime,confirmTime,paymentType,payStatus,shippingAmount FROM orders WHERE appId = ? AND userId = ? AND orderStatus != 9";
    szQuery += where;
    szQuery += ' ORDER BY orders.addTime DESC LIMIT ?,? ';
    let rows = await shop.query(szQuery,[appId,userId,offset,limit]);
    if (rows && rows.length) {
      for (let i in rows) {
        let order = rows[i];
        szQuery = 'SELECT productId,skuId,productName,buyCount,unitAmount,thumbnail,description FROM order_products AS o LEFT JOIN products AS p ON o.productId = p.id WHERE orderId = ? AND o.appId = ?';
		    let products = await shop.query(szQuery,[order.id,appId]);
        let totalCount = 0;
        for (var n in products) {
          totalCount += products[n].buyCount;
        }
        order.totalCount = totalCount;
		    order.products = products;
      }
    }
    return rows;
  };

  /*订单详情*/
  const _orderInfo = async (appId,userId,orderNum) =>{
    let szQuery = 'SELECT orders.id,orderNo,orderStatus,shipType,shippingAmount,productAmount,payAmount,orderAmount,consignee,province,city,district,address,mobile,addTime,confirmTime,paymentType,payStatus FROM orders WHERE orderNo = ? AND appId = ? AND userId = ?';
    let rows = await shop.query(szQuery,[orderNum,appId,userId]);
    if (rows && rows.length) {
      let order = rows[0];
      szQuery = 'SELECT productId,skuId,productName,buyCount,unitAmount,thumbnail,description FROM order_products AS o LEFT JOIN products AS p ON o.productId = p.id WHERE orderId = ? AND o.appId = ?';
      let products = await shop.query(szQuery,[order.id,appId]);
      order.products = products;
      var deliver = {};
  		deliver.deliveryCost = order.shippingAmount;
  		szQuery = 'SELECT * FROM order_traces WHERE orderId = ?';
  		var traces = await shop.query(szQuery,[order.id]);
  		if (traces && traces.length){
  			deliver.deliveryName = traces[0].shipperName;
  			var trace = JSON.parse(traces[0].traces);
  			if (trace && trace.length){
  				deliver.lastTrace = trace[trace.length - 1];
  			}else{
  				deliver.lastTrace = {};
  			}
  		}else{
  			deliver.lastTrace = {};
  		}
      order.delivers = deliver;
      return order;
    }
    return {};
  }

  /*提交订单*/
  const _addOrder = async (userId,appId,addTime,orderNo,productAmount,shippingAmount,orderAmount,payAmount,orderStatus,consignee,province,city,district,address,mobile,shipType,paymentType,list) => {
    let szQuery = "INSERT INTO orders(userId,appId,addTime,orderNo,productAmount,shippingAmount,orderAmount,payAmount,orderStatus,consignee,province,city,district,address,mobile,shipType,paymentType) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    let params = [userId,appId,addTime,orderNo,productAmount,shippingAmount,orderAmount,payAmount,orderStatus,consignee,province,city,district,address,mobile,shipType,paymentType];
    let ret = await shop.query(szQuery,params);
    if (ret.affectedRows > 0) {
      let orderId = ret.insertId;
      let skuIds = '';
      for(var i in list) {
        szQuery = 'REPLACE INTO order_products(productId,skuId,orderId,buyCount,appId,unitAmount) VALUES(?,?,?,?,?,?)';
        let res = await shop.query(szQuery,[list[i].productId,list[i].skuId,orderId,list[i].selectedNumber,appId,list[i].selectedAmount]);
        skuIds += res.affectedRows > 0 ? parseInt(list[i].skuId) + ',' : '';
        if (res.affectedRows > 0) {
          await skuService.updateSkuStock(appId,list[i].skuId,list[i].productId,list[i].count);
        }
      }
      skuIds = skuIds.substring(0,skuIds.length -1);
      let flag = await cartService.clearCart(appId,userId,skuIds);
      return orderNo;
    }
    return '';
  };

  /*验证商品总金额*/
  const _checkOrderAmountMulit = async (orderAmount,list) => {
      let total = 0;
      for(let i in list) {
        total += list[i].selectedNumber * list[i].selectedAmount;
      }
      console.log("orderAmount: " + orderAmount + " total: " + total);
      return orderAmount == parseFloat(total.toFixed(2)) ? true : false;
  };

  /*验证订单实际支付金额*/
  const _checkPayAmount = async (orderAmount,payAmount,shipAmount) =>{
    let pay = parseFloat(orderAmount) + parseFloat(shipAmount);
    return payAmount == parseFloat(pay.toFixed(2)) ? true : false;
  };

  /*生成订单号*/
  const _getOrderNum = async (appId) =>{
    let orderNum = new Date().getTime();
    console.log(orderNum);
    return appId + "" + orderNum;
  };

  /*验证订单是否存在*/
  const _checkOrderExist = async (appId,userId,orderNum,price) => {
    let szQuery = "SELECT * FROM orders WHERE appId = ? AND userId = ? AND orderNo = ?";
    let rows = await shop.query(szQuery,[appId,userId,orderNum]);
    if (rows && rows.length) {
      return rows[0]['payAmount'] == price ? true : false;
    }
    return false;
  };

  /*获取订单状态*/
  const _checkOrderStatus = async (appId,userId,orderNum,orderStatus) => {
    let szQuery = "SELECT id,orderStatus FROM orders WHERE appId = ? AND userId = ? AND orderNo = ?";
    let rows = await shop.query(szQuery,[appId,userId,orderNum]);
    if (rows && rows.length) {
      return rows[0]['orderStatus'] == orderStatus ? true : false;
    }
    return false;
  };

  /*获取订单*/
  const _getOrderByOrderNum = async (appId,userId,orderNum) => {
    let szQuery = "SELECT * FROM orders WHERE appId = ? AND userId = ? AND orderNo = ?";
    let rows = await shop.query(szQuery,[appId,userId,orderNum]);
    if (rows && rows.length) {
      let order = rows[0];
      szQuery = 'SELECT productId,skuId,productName,buyCount,unitAmount,thumbnail,description FROM order_products AS o LEFT JOIN products AS p ON o.productId = p.id WHERE orderId = ? AND o.appId = ?';
      let products = await shop.query(szQuery,[order.id,appId]);
      order.products = products;
      return order;
    }
    return null;
  };

  const _getOrderByOrderNo = async (orderNum) => {
      let szQuery = "SELECT * FROM orders WHERE orderNo = ?";
      let rows = await shop.query(szQuery,[orderNum]);
      return rows && rows.length ? rows[0] : null;
  };

  /*更新订单状态*/
  const _updateOrderStatus = async (appId,userId,orderNum,orderStatus) => {
    if (orderStatus == 5) {
      let confirmTime = Math.floor(new Date().getTime() / 1000);
      let szQuery = "UPDATE orders SET orderStatus = ?,confirmTime = ? WHERE appId = ? AND userId = ? AND orderNo = ?";
      let ret = await shop.query(szQuery,[orderStatus,confirmTime,appId,userId,orderNum]);
      return ret.affectedRows > 0 ? true : false;
    } else {
      let szQuery = "UPDATE orders SET orderStatus = ? WHERE appId = ? AND userId = ? AND orderNo = ?";
      let ret = await shop.query(szQuery,[orderStatus,appId,userId,orderNum]);
      return ret.affectedRows > 0 ? true : false;
    }
  };

  const _updateOrderStatusByOrderNum = async (orderNum,orderStatus) => {
    let time = Math.floor(new Date().getTime() / 1000);
    if (orderStatus == 3) {
      let szQuery = "UPDATE orders SET orderStatus = ?,payTime = ? WHERE orderNo = ?";
      let ret = await shop.query(szQuery,[orderStatus,time,orderNum]);
      return ret.affectedRows > 0 ? true : false;
    } else if (orderStatus == 5) {
      let szQuery = "UPDATE orders SET orderStatus = ?,confirmTime = ? WHERE orderNo = ?";
      let ret = await shop.query(szQuery,[orderStatus,time,orderNum]);
      return ret.affectedRows > 0 ? true : false;
    } else {
      let szQuery = "UPDATE orders SET orderStatus = ? WHERE appId = ? AND userId = ? AND orderNo = ?";
      let ret = await shop.query(szQuery,[orderStatus,appId,userId,orderNum]);
      return ret.affectedRows > 0 ? true : false;
    }
  };

  /*更新订单操作*/
  const _doOrderAction = async (appId,userId,orderId,actionType,actionStatus,actionNote,actionMsg) => {
    let addTime = Math.floor(new Date().getTime() / 1000);
    let szQuery = "INSERT INTO order_actions (appId,userId,orderId,actionType,actionStatus,actionTime,actionNote,actionMsg) VALUES(?,?,?,?,?,?,?,?)";
    let ret = await shop.query(szQuery,[appId,userId,orderId,actionType,actionStatus,addTime,actionNote,actionMsg]);
    return ret.affectedRows > 0 ? true : false;
  };

  return {
    addOrder : _addOrder,
    checkOrderAmountMulit: _checkOrderAmountMulit,
    checkPayAmount: _checkPayAmount,
    getOrderNum: _getOrderNum,
    list: _orderlist,
    info: _orderInfo,
    checkOrderExist: _checkOrderExist,
    checkOrderStatus: _checkOrderStatus,
    getOrderByOrderNum: _getOrderByOrderNum,
    updateOrderStatus: _updateOrderStatus,
    doOrderAction: _doOrderAction,
    getOrderByOrderNo: _getOrderByOrderNo,
    updateOrderStatusByOrderNum: _updateOrderStatusByOrderNum
  }
}();

module.exports = OrderService;
